<?php

class techoratiplugin extends WikiPlugin
{
	function techoratiplugin() {
		$this->add_macro('technorati', 'technorati');
		$this->add_event('post_save', 'on_post_save');
	}

	function technorati($tags, $inhtml = false)
	{
		global $db, $mwconfig, $wiki, $rewrite;
		$output = '';
		if($tags == '') {
			if($inhtml) $output .= '<div class="technorati">';
			foreach((array)$wiki->technorati as $tag) {
				if($inhtml) {
					$output .= "<a href=\"http://technorati.com/tags/{$tag}\">{$tag}</a> ";
				}
				else {
					$output .= "<category>{$tag}</category>\n";
				}
			}
			if($inhtml) $output .= '</div>';
			unset($wiki->technorati);
		}
		else {
			preg_match_all('/(["\']).+?\\1(?!\\S)|(?!")[\\S]+/', $tags, $matches);
			foreach($matches[0] as $match) {
				$wiki->technorati[] = trim($match, '"\'');
			}
		}
		
		return $output;
	}
	
	function on_post_save($page, $data)
	{
		global $rewrite, $mwconfig;
		if(preg_match('/{{technorati(:.+?)?}}/i', $data['pagecontent'])) {
			//do technorati ping!
			$this->pingservice("http://rpc.technorati.com:80/rpc/ping", $rewrite->get_link(array('page'=>$page)));
		}
	}
	
	function pingservice($pingserver, $url) {
	  $pingserver = parse_url($pingserver);
	  if(!isset($pingserver['port'])) $pingserver['port'] = 80;
	
		$fp = fsockopen($pingserver['host'], $pingserver['port'], $errnum, $errstr);
		if (!$fp) {
			owd("Couldn't open socket to ping server {$pingserver}");
		}
		else {
			$message = "<?xml version=\"1.0\"?"."><methodCall><methodName>weblogUpdates.ping</methodName>";
			$message .= "<params><param><value>{$mwconfig->wikiname}</value></param>";
			$message .= "<param><value>{$url}</value></param>";
			$message .= "</params></methodCall>";
			fputs($fp, "POST {$pingserver['path']} HTTP/1.1\r\n");
			fputs($fp, "Host: {$pingserver['host']}\r\n");
			fputs($fp, "User-Agent: MicroWiki/3.0\r\n");
			fputs($fp, "Content-Type: text/xml\r\n");
			fputs($fp, "Content-length: ".strlen($message)."\r\n\r\n");
			fputs($fp,$message);
			$output = "";
			while (!feof($fp)) $output .= fgets($fp,4096);
			fclose($fp);
		}
		$output = preg_replace("/.*<\/boolean>/si","",$output);
		$output = preg_replace("/.*<value>/si","",$output);
		$output = preg_replace("/<\/value>.*/si","",$output);
		owd($output);
	}	

}


?>
